import { defineStore } from 'pinia';
import { store } from '@/store';
import { ACCESS_TOKEN, CURRENT_USER, IS_SCREENLOCKED } from '@/store/mutation-types';
import { ResultEnum } from '@/enums/httpEnum';

import { getUserInfo as getUserInfoApi, login } from '@/api/system/user';
import { storage } from '@/utils/Storage';

export type UserInfoType = {
  // TODO: add your own data
  account: string;
  role: string;
  token: string;
};

export interface IUserState {

  //非必须
  token: string;
  username: string;
  welcome: string;
  avatar: string;
  permissions: any[];
  info: UserInfoType;


}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: storage.get(ACCESS_TOKEN, ''),
    username: '',
    welcome: '',
    avatar: '',
    permissions: [],
    info: storage.get(CURRENT_USER, {}),
  }),
  getters: {
    getToken(): string {
      return this.token;
    },
    getAvatar(): string {
      return this.avatar;
    },
    getNickname(): string {
      return this.username;
    },
    getPermissions(): [any][] {
      return this.permissions;
    },
    getUserInfo(): UserInfoType {
      return this.info;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    setUserInfo(info: UserInfoType) {
      this.info = info;
    },


    // 登录
    async login(params: any) {
      
      //axios
      
  
      
      const response = await login(params);
      
      console.log(response.data)
      
      // result code变量里面 response.data
      // 数据存储在data里面
      const { result, code } = response.data;
      console.log(result,code)


      if (code === ResultEnum.SUCCESS) {
       
        //200
        const ex = 7 * 24 * 60 * 60;//过期时间

        //storage存储
        storage.set(ACCESS_TOKEN, result.token, ex);
        //当前用户的信息
        storage.set(CURRENT_USER, result, ex);

        storage.set(IS_SCREENLOCKED, false);
       
        //userStore存储
        this.setToken(result.token);
        //
        this.setUserInfo(result);

        //
      }
      return response.data;
    },

    // 获取用户权限
    async getInfo() {
      
      // 截断 简单粗暴设置
     
     // 
      const res = storage.get(CURRENT_USER, {})
      var permissionsListPre = [{},{},{},{},{}]
      
      
      if (res.role == 0) {
        console.log("管理员")
        permissionsListPre = [{
          label: '管理员',
          value: 'admin',
        }]
      }else if(res.role == 1){
        console.log("学生")
        permissionsListPre = [{
          label: '学生',
          value: 'student',
        }]
      }else if(res.role == 2){
        console.log("教师")
        permissionsListPre = [{
          label: '教师',
          value: 'teacher',
        }]
      }else if(res.role == 3){
        console.log("实验员")
        permissionsListPre = [{
          label: '实验员',
          value: 'labAmdin',
        }]
      }


      
      const result = await getUserInfoApi();

      result.permissions = permissionsListPre

      console.log("getUserInfoApi-result",result)

      if (result.permissions && result.permissions.length) {
        
        
        const permissionsList = result.permissions;
        // const permissionsList = permissionsListPre;

        // console.log("after","permissionsList",permissionsList ,"permissionsListPre",permissionsListPre)

        this.setPermissions(permissionsList);
        this.setUserInfo(result);


      } else {
        throw new Error('form (getUserInfoApi())g etInfo: permissionsList must be a non-null array !');
      }
      this.setAvatar(result.avatar);
      return result;
    },

    // 登出
    async logout() {
      this.setPermissions([]);
      this.setUserInfo({ name: '', email: '' });
      storage.remove(ACCESS_TOKEN);
      storage.remove(CURRENT_USER);
    },
  },
});

// Need to be used outside the setup
export function useUser() {
  
  return useUserStore(store);

}
